package com.boarsoft.rpc.generalize;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.springframework.beans.BeanWrapperImpl;

import com.boarsoft.common.util.BeanUtil;
import com.boarsoft.common.util.JsonUtil;

public class RpcGenObj extends RpcGenType {
	private static final long serialVersionUID = -4750605951992217194L;

	protected Map<String, Object> map = new HashMap<>();

	protected RpcGenObj() {
	}

	public RpcGenObj(String clazzName) {
		this.clazzName = clazzName;
	}

	public RpcGenObj(String clazzName, Map<String, Object> map) {
		this.clazzName = clazzName;
		this.map = map;
	}

	@Override
	public String toString() {
		return JsonUtil.toJSONString(this);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Object specialize() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		Object ro = this.create(clazzName);
		// 用Map中的键值填充目标对象的属性
		BeanWrapperImpl bw = new BeanWrapperImpl(ro);
		for (Entry<String, Object> en : map.entrySet()) {
			String k = en.getKey();
			Object so = en.getValue();
			Object to = so;
			if (so instanceof RpcGenType) {
				to = ((RpcGenType) so).specialize();
			} else if (so instanceof Map) {
				// 如果泛化属性是mMap，但目标对象的属性k不是Map，则尝试如下转换，反之不作处理
				Class<?> pc = bw.getPropertyType(k);
				if (!pc.isAssignableFrom(Map.class)) {
					// 这种只能针对目标对象属性的类型是可实例化的类而不是接口或抽象类的情况
					to = pc.newInstance();
					BeanUtil.fillObjectWithMap(to, (Map<String, Object>) so);
				}
			}
			bw.setPropertyValue(k, to);
		}
		return ro;
	}

	// @Override
	public int size() {
		return map.size();
	}

	// @Override
	public boolean isEmpty() {
		return map.isEmpty();
	}

	// @Override
	public boolean containsKey(String key) {
		return map.containsKey(key);
	}

	// @Override
	public boolean containsValue(Object value) {
		return map.containsValue(value);
	}

	// @Override
	public Object get(String key) {
		return map.get(key);
	}

	// @Override
	public Object put(String key, Object value) {
		return map.put(key, value);
	}

	// @Override
	public Object remove(String key) {
		return map.remove(key);
	}

	// @Override
	public void putAll(Map<String, ? extends Object> m) {
		map.putAll(m);
	}

	// @Override
	public void clear() {
		map.clear();
	}

	// @Override
	public Set<String> keySet() {
		return map.keySet();
	}

	// @Override
	public Collection<Object> values() {
		return map.values();
	}

	// @Override
	public Set<java.util.Map.Entry<String, Object>> entrySet() {
		return map.entrySet();
	}

	public Map<String, Object> getMap() {
		return map;
	}

	public void setMap(Map<String, Object> map) {
		this.map = map;
	}
}
